//读取配置文件，变量config的类型是Object类型
const config = require('./config');
// 微信必须的模块函数
// node内置的加密模块
const crypto = require('crypto');
// 用户获取签名的函数
const sign = require('./sign');
// 引入转义方法
const X2JS = require('./x2j/x2js/we-x2js');
const xml2js = require('xml2js')
// 导入云函数的
const db = uniCloud.database()

// 接受扫码事件
async function scanAction(params){
	// 接收获得的参数 这里获得params {ToUserName,FromUserName,CreateTime,MsgType,Event,EventKey,Ticket}
	// 返回想要放回的值 返回 scene_id
	let replyData='你本次扫描获得的二维码代号是'+params.EventKey
	// 发送文字
	// 获取数据库的值，然后做相应的操作
	let serverData=await db.collection('qrcode').where({
		ticket:params.Ticket
	}).get()
	if(serverData.length===0){
		// 扫码无效，没有结果
		replyData='此二维码为在后台注册'
	}
	let text = {
		"touser": params.FromUserName,
		"msgtype": "text",
		"text": {
			"content": replyData
		}
	}
	await sendCustomerMsg(text)
	return 'success'
}

// xml 转json
function xmlToJson(str) {
	var x2js = new X2JS();
	return x2js.xml2js(str).xml
	// 第二种方法有待优化
	// const parseString = xml2js.parseString
	// parseString(str, (err, result) => {
	// 	if (err) {
	// 		return false
	// 	} else {
	// 		console.log(result)
	// 		return result
	// 	}
	// })
}
// jons 转 xml
function jsonToXml(obj) {
	// var x2js = new X2JS();
	// return x2js.js2xml(str)
	let xml = '<xml>'
	for (let key in obj) {
		if (key && obj[key]) {
			let item = key !== 'CreateTime' ? `<${key}><![CDATA[${obj[key]}]]></${key}>` : `<${key}>${body[key]}</${key}>`
			xml += item
		}
	}
	xml += '</xml>'
	return xml
}

// 加密sha1函数
function sha1(str) {
	let shasum = crypto.createHash("sha1");
	return shasum.update(str, 'utf-8').digest("hex");
}
// 公众号授权
function wechatAuth(params) {
	let reqArray = [params.nonce, params.timestamp, config.WECHAT_TOKEN];
	let sortStr = reqArray.join(''); //连接数组
	let sha1Str = sha1(sortStr.toString().replace(/,/g, ""));
	if (sha1Str === params.signature) {
		return params.echostr
	} else {
		return '授权失败'
	}
}

async function sendCustomerMsg(data) {
	console.log('data', data)
	let access_token = await getToken()
	let sendUrl =
		`https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${access_token}`
	let sendRes = await uniCloud.httpclient.request(sendUrl, {
		method: 'POST',
		data: JSON.stringify(data),
		dataType: 'json'
	})
	console.log(sendRes)
	// if(sendRes.data.errcode===0&&sendRes.data.errmsg==='ok'){
	// 	return {
	// 		data:'success',
	// 		status:200
	// 	}
	// }else{
	// 	return {
	// 		msg:'服务器出错',
	// 		data:false,
	// 		status:400
	// 	}
	// }
}

// 被动消息回复
async function WeixinChatReply(params) {
	/* 
	 params{xml 包含微信发来给我们的信息}
	 */
	if (!params.json.MsgType) {
		return
	}
	console.log('params', params)
	let wxData = params.json
	// 如果是文字：那么就返回一下内容
	// 分发不同类型的消息--并组织返回
	switch (wxData.MsgType) {
		case 'event':
			if (wxData.EventKey === 'V1001_GOOD'&&wxData.Event==='CLICK') {
				let musicData = {
					Title: 'Good Time',
					Description: '为你推送你喜欢的音乐',
					MusicUrl: 'http://m10.music.126.net/20201223155240/4fdc693c512d941c90a92811c65df89b/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3057700342/0090/22ca/dd84/1cb0004a85d8838f95dcc147852d49aa.mp3',
					HQMusicUrl: 'http://m10.music.126.net/20201223155240/4fdc693c512d941c90a92811c65df89b/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3057700342/0090/22ca/dd84/1cb0004a85d8838f95dcc147852d49aa.mp3',
					thumb_media_id: 'qcCkD-Hx8jftrj1daXMUcjeeAknmbbDB8PAq_BUTcPc20JhBzqUPGg4dZu2GZGhl'
				}
				let replyData = '为你推荐贵阳的歌曲'
				// 发送音乐
				let music = {
					"touser": params.openid,
					"msgtype": "music",
					"music": {
						"title": musicData.Title,
						"description": musicData.Description,
						"musicurl": musicData.MusicUrl,
						"hqmusicurl": musicData.HQMusicUrl,
						"thumb_media_id": musicData.thumb_media_id
					}
				}
				await sendCustomerMsg(music)
				// 发送文字
				let text = {
					"touser": params.openid,
					"msgtype": "text",
					"text": {
						"content": replyData
					}
				}
				await sendCustomerMsg(text)
				return 'success'
			}else if(wxData.Event==='SCAN'&&wxData.Ticket){
				return scanAction(wxData)
			}else{
				return 'success'
			}
			break;
		case 'text':
			let xml = ''
			if (wxData.Content === '音乐') {
				let musicData = {
					Title: 'Good Time',
					Description: '为你推送你喜欢的音乐',
					MusicUrl: 'http://m10.music.126.net/20201223155240/4fdc693c512d941c90a92811c65df89b/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3057700342/0090/22ca/dd84/1cb0004a85d8838f95dcc147852d49aa.mp3',
					HQMusicUrl: 'http://m10.music.126.net/20201223155240/4fdc693c512d941c90a92811c65df89b/ymusic/obj/w5zDlMODwrDDiGjCn8Ky/3057700342/0090/22ca/dd84/1cb0004a85d8838f95dcc147852d49aa.mp3',
					thumb_media_id: 'qcCkD-Hx8jftrj1daXMUcjeeAknmbbDB8PAq_BUTcPc20JhBzqUPGg4dZu2GZGhl'
				}
				let replyData = '总在夜深人静的时候想起这首歌'
				// 发送音乐
				let music = {
					"touser": params.openid,
					"msgtype": "music",
					"music": {
						"title": musicData.Title,
						"description": musicData.Description,
						"musicurl": musicData.MusicUrl,
						"hqmusicurl": musicData.HQMusicUrl,
						"thumb_media_id": musicData.thumb_media_id
					}
				}
				await sendCustomerMsg(music)
				// 发送文字
				let text = {
					"touser": params.openid,
					"msgtype": "text",
					"text": {
						"content": replyData
					}
				}
				await sendCustomerMsg(text)
				return 'success'
			} else {
				let replyData = '你发的内容是' + wxData.Content
				let xml =
					`<xml>
			<ToUserName><![CDATA[${wxData.FromUserName}]]></ToUserName>
			<FromUserName><![CDATA[${wxData.ToUserName}]]></FromUserName>
			<CreateTime>${wxData.CreateTime}</CreateTime>
			<MsgType><![CDATA[text]]></MsgType>
			<Content><![CDATA[${replyData}]]></Content>
			</xml>`
			}
			console.log(xml)
			return xml
			break;
		case 'image':
			break;
		case 'video':
			break;
		case 'music':
			break;
		case 'news':
			break;
		default:
			return 'success'
			break;
	}

	// 如果是其他类型，就返回对方发来的内容即可
	return 'success'
	// 分发不同类型的消息--并组织返回
	// switch (wxData.Content) {
	// 	case '文字':
	// 		break;
	// 	case '照片':
	// 		break;
	// 	case 'video':
	// 		break;
	// 	case 'music':
	// 		break;
	// 	case 'news':
	// 		break;
	// 	default:
	// 		break;
	// }

}

// 发送模板消息
async function WeixinMessageReply(params) {
	if (!params.MsgType) {
		return
	}
	let access_token = await getToken()
	if (!access_token) {
		return {
			msg: 'token不存在或已经达到最高限度'
		}
	}

	let data = {}
	// 接收客服端发来的文字
	if (params.MsgType === 'text') {
		data = {
			"touser": params.FromUserName,
			"template_id": "uUUT4QScSvbbXPRmq4nHebGVL3qI-T2ZoFNOau79qJU",
			"url": "http://vlog.minihack.cn",
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"Content": {
					"value": params.Content,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	// 接受客户端发来的照片
	if (params.MsgType === 'image') {
		data = {
			"touser": params.FromUserName,
			"template_id": "FvfLEapAAmklbbTUwr1_B_IIKghW85ES3R_xndTN6_M",
			"url": params.PicUrl,
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"PicUrl": {
					"value": params.PicUrl,
					"color": "#173177"
				},
				"MediaId": {
					"value": params.MediaId,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	// 接受客户端发来的语音消息
	if (params.MsgType === 'voice') {
		data = {
			"touser": params.FromUserName,
			"template_id": "U7Evo1U5IvtD-bOJTBzTKeXEDJLxvnyOriozkixveF8",
			"url": "http://vlog.minihack.cn",
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"Format": {
					"value": params.Format,
					"color": "#173177"
				},
				"MediaId": {
					"value": params.MediaId,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	// 接受客户端发来的视频消息
	if (params.MsgType === 'video') {
		data = {
			"touser": params.FromUserName,
			"template_id": "87pVgqWTdPUjGYzwHIpXOwSCr7ZTiPQqBlT_DTqYrvo",
			"url": "http://vlog.minihack.cn",
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"ThumbMediaId": {
					"value": params.ThumbMediaId,
					"color": "#173177"
				},
				"MediaId": {
					"value": params.MediaId,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	// 接受客户端发来的小视频消息
	if (params.MsgType === 'shortvideo') {
		data = {
			"touser": params.FromUserName,
			"template_id": "9TV62S7Z8wI0LX1Fhi6B9WVVUgR8JIKexVZdjyjy5Is",
			"url": "http://vlog.minihack.cn",
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"ThumbMediaId": {
					"value": params.ThumbMediaId,
					"color": "#173177"
				},
				"MediaId": {
					"value": params.MediaId,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	// 接受客户端发来的地理位置消息
	if (params.MsgType === 'location') {
		data = {
			"touser": params.FromUserName,
			"template_id": "1vUKRhcNkJoe9-hlH43syx5dooV5vb-7Lw2XSNOkv_k",
			"url": "http://vlog.minihack.cn",
			"data": {
				"ToUserName": {
					"value": params.ToUserName,
					"color": "#173177"
				},
				"FromUserName": {
					"value": params.FromUserName,
					"color": "#173177"
				},
				"MsgType": {
					"value": params.MsgType,
					"color": "#173177"
				},
				"Location_X": {
					"value": params.Location_X,
					"color": "#173177"
				},
				"Location_Y": {
					"value": params.Location_Y,
					"color": "#173177"
				},
				"Scale": {
					"value": params.Scale,
					"color": "#173177"
				},
				"Label": {
					"value": params.Label,
					"color": "#173177"
				},
				"MediaId": {
					"value": params.MediaId,
					"color": "#173177"
				},
				"MsgId": {
					"value": params.MsgId,
					"color": "#173177"
				},
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
	}
	if (params.MsgType === 'event' && params.Event === 'subscribe') {
		data = {
			"touser": params.FromUserName,
			"template_id": "CuqFpWJO24LXAHI3JZplvodx6F9Eghz05EUpeu_wrXw",
			"url": "http://vlog.minihack.cn",
			"data": {
				"CreateTime": {
					"value": params.CreateTime,
					"color": "#173177"
				}
			}
		}
		console.log('扫码', params)
	}
	if (params.MsgType === 'event' && params.Event !== 'subscribe') {
		return {
			msg: '暂时不处理'
		}
	}
	let access_tokenApiUrl =
		`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`
	let pushRes = await uniCloud.httpclient.request(access_tokenApiUrl, {
		method: 'POST',
		data: JSON.stringify(data),
		dataType: 'json'
	})
}

// 发送模板消息
async function WeixinMessagePush(params) {
	let access_token = await getToken()
	if (!access_token) {
		return {
			msg: 'token不存在或已经达到最高限度'
		}
	}
	let data = {
		"touser": params.openid,
		"template_id": "Rql-hWyHqZjyf0aHUNttsk62S-zNgpW0yB1yet8qKzo",
		"url": "http://vlog.minihack.cn",
		"data": {
			"nickname": {
				"value": params.nickname,
				"color": "#173177"
			}
		}
	}
	let access_tokenApiUrl =
		`https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`
	let pushRes = await uniCloud.httpclient.request(access_tokenApiUrl, {
		method: 'POST',
		data: JSON.stringify(data),
		dataType: 'json'
	})
}

// 获取签名
async function getSignature(params) {
	// 1.获取ticket--
	let jsapi_ticket = ''
	let cloudTicket = await db.collection('jsapi_ticket').orderBy("expires_in", "asc").limit(1).get()
	// 查看jsapi_ticket是否过期
	if (cloudTicket.data.length > 0 && parseInt(cloudTicket.data[0].expires_in) > parseInt(new Date().getTime() / 1000)) {
		jsapi_ticket = cloudTicket.data[0].jsapi_ticket
	} else {
		var tokenApiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		// 获取token
		let getToken = await uniCloud.httpclient.request(tokenApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		let token = getToken.data.access_token
		// 获取Ticket
		var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
		let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		// 拿到最新的票据
		jsapi_ticket = getTicket.data.ticket
		let expires_in = parseInt(new Date().getTime() / 1000) + parseInt(getTicket.data.expires_in)
		// 存到数据库
		if (cloudTicket.data.length > 0) {
			await db.collection('jsapi_ticket').doc(cloudTicket.data[0]._id).update({
				jsapi_ticket,
				expires_in
			})
		} else {
			await db.collection('jsapi_ticket').add({
				jsapi_ticket,
				expires_in
			})
		}
	}
	// 获取签名
	let signature = sign(jsapi_ticket, params.url)
	signature.appId = config.appid
	return signature
}

// 通过appid 和 AppSecret 获取token 
async function getToken() {
	let access_token = ''
	// 通过appid 和 scret 获取微信服务器的access_token
	// 判断服务器是否存有access_token并且还没有过期
	// 如果过期，则从新获取
	// 未过期，直接返回服务器保存的token
	let cloudToken = await db.collection('wx_token').orderBy("expires_in", "asc").limit(1).get()
	if (cloudToken.data.length > 0 && parseInt(cloudToken.data[0].expires_in) > parseInt(new Date().getTime() / 1000)) {
		access_token = cloudToken.data[0].access_token
	} else {
		let apiUrl =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${config.appid}&secret=${config.appsecret}`
		const res = await uniCloud.httpclient.request(apiUrl, {
			method: 'POST',
			data: {},
			dataType: 'json'
		})
		access_token = res.data.access_token
		if (!access_token) {
			return {
				msg: 'token不存在或已经达到最高限度'
			}
		}
		let expires_in = parseInt(new Date().getTime() / 1000) + parseInt(res.data.expires_in)
		// 存到数据库
		if (cloudToken.data.length > 0) {
			await db.collection('wx_token').doc(cloudToken.data[0]._id).update({
				access_token,
				expires_in
			})
		} else {
			await db.collection('wx_token').add({
				access_token,
				expires_in
			})
		}

	}
	return access_token
}

// 获取票据
async function getTicket() {
	let token = await getToken()
	if (!access_token) {
		return {
			msg: 'token不存在或已经达到最高限度'
		}
	}
	// 获取Ticket
	var ticketApiUrl = `https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=${token}&type=jsapi`
	let getTicket = await uniCloud.httpclient.request(ticketApiUrl, {
		method: 'POST',
		data: {},
		dataType: 'json'
	})
	let jsapi_ticket = getTicket.data.ticket
	return getTicket
}

module.exports = {
	getTicket,
	getToken,
	getSignature,
	WeixinMessagePush,
	WeixinMessageReply,
	wechatAuth,
	jsonToXml,
	xmlToJson,
	WeixinChatReply
}
